package cn.jcby.app.lebu.utils;

import org.geotools.geojson.geom.GeometryJSON;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @author: lihaotian
 * @since: 2023/12/11 01:07
 * @description
 **/
public class GeoToolsUtils {

    /**
     *  WKT 格式转化为 GeoJson
     * @Param: 传入WKT形式的字符串
     */

    public static String wktToGeoJson(String wktPoint){
        WKTReader reader = new WKTReader();
        Geometry geometry = null;
        try {
            geometry = reader.read(wktPoint);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(geometry.toText());
        StringWriter writer = new StringWriter();
        GeometryJSON g = new GeometryJSON();
        try {
            g.write(geometry, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String result = writer.toString();
        return result;
    }


    /**
     *  GeoJson 格式转化为 WKT
     * @Param: 传入GeoJson形式的字符串
     */
    public static String geoJsonToWkt(String geoJson) {
        GeometryJSON gjson = new GeometryJSON();
        Reader reader = new StringReader(geoJson);
        Geometry geometry = null;
        try {
            geometry = gjson.read(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String wkt = geometry.toText();
        return wkt;
    }




    public static Point getPoint(Double longitude, Double latitude)  {
        GeometryFactory factory = new GeometryFactory();
        return factory.createPoint(new Coordinate(longitude, latitude));
    }

    public static void main(String[] args) throws InterruptedException {
        String wkt = "LINESTRING(116.397428 39.90923,116.397428 39.90923,116.397428 39.90923)";
        String geoJson = wktToGeoJson(wkt);
        System.out.println(geoJson);
        String wkt2 = geoJsonToWkt(geoJson);
        System.out.println(wkt2);
    }


}
